package com.zhentao.subscription.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.subscription.common.R;
import com.zhentao.subscription.domain.dto.TaskCreateDTO;
import com.zhentao.subscription.domain.entity.SubscriptionTask;
import com.zhentao.subscription.service.TaskService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/subscription/tasks")
@CrossOrigin(origins = "http://localhost:5173")
public class TaskController {

    private final TaskService taskService;

    public TaskController(TaskService taskService) {
        this.taskService = taskService;
    }

    @PostMapping
    public R<Long> createOrUpdate(@Valid @RequestBody TaskCreateDTO dto) {
        return R.ok(taskService.createOrUpdateTask(dto));
    }

    @DeleteMapping("/{id}")
    public R<Void> delete(@PathVariable Long id) {
        taskService.deleteTask(id);
        return R.ok();
    }

    @GetMapping
    public R<Page<SubscriptionTask>> page(@RequestParam(defaultValue = "1") int pageNo,
                                          @RequestParam(defaultValue = "10") int pageSize,
                                          @RequestParam(required = false) String keyword) {
        return R.ok(taskService.pageTasks(pageNo, pageSize, keyword));
    }

    @PostMapping("/{id}/dispatch")
    public R<Void> dispatch(@PathVariable Long id) {
        taskService.triggerDispatch(id);
        return R.ok();
    }

    @GetMapping("/{id}")
    public R<SubscriptionTask> getById(@PathVariable Long id) {
        return R.ok(taskService.getById(id));
    }
}

